import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:joyagoo/pages/widget/JoyEmptyWidget.dart';
import 'package:joyagoo/pages/widget/Joy_NoNetworkTip_Widget.dart';
import '../config/app_colors.dart';
import '../config/app_url_address.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/category_manager.dart';
import 'joy_category_content_page.dart';
import 'joy_home_bloc.dart';

class JoyCategoryPage extends StatefulWidget {
  const JoyCategoryPage({super.key});

  @override
  State<JoyCategoryPage> createState() => _JoyCategoryPageState();
}

class _JoyCategoryPageState extends State<JoyCategoryPage>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  TabController? _tabController;  // 🔥 修改为可空类型，防止未初始化访问
  
  // 统一的颜色配置 - 使用新的主题色
  static const List<Color> _unifiedGradient = [Color(0xFFFF6B35), Color(0xFFFF6B35)];
  static const Color _unifiedColor = Color(0xFFFF6B35);
  late JoyHomeBloc homeBloc;
  String error_joy = "Loading...";
  bool isNetError_kkb = false;
  String errorImage_kkb = "";
  bool isError = false; // 🔥 网络错误状态标记
  bool isTabControllerInitialized = false; // 🔥 添加TabController初始化状态标记
  bool isFirstLaunch = true; // 🔥 标记是否为首次启动

  // 🔥 移除硬编码分类数据，使用全局分类管理器
  // 备用分类数据（仅在网络完全失败时使用）
  List  fallbackCategories = [
    {'icon': '👟', 'categoryName': 'Shoes',"categoryId":1},
    {'icon': '👕', 'categoryName': 'T-Shirt',"categoryId":2},
    {'icon': '🧦', 'categoryName': 'Shorts',"categoryId":3},
    {'icon': '🦺', 'categoryName': 'Hoodie/Sweater',"categoryId":4},
    {'icon': '👔', 'categoryName': 'Suits',"categoryId":5},
    {'icon': '🧤', 'categoryName': 'Jacket/Sweatshirt',"categoryId":6},
    {'icon': '👖', 'categoryName': 'Pants/Jeans',"categoryId":7},
    {'icon': '🎩', 'categoryName': 'Accessories',"categoryId":8},
    {'icon': '🎁', 'categoryName': 'Others',"categoryId":69},
    {'icon': '🎁', 'categoryName': 'Electronics',"categoryId":70},
  ];

  // 🔥 移除硬编码的分类产品列表数据，使用全局分类管理器

  @override
  void initState() {
    super.initState();
    // 🔥 添加应用生命周期监听器，用于检测网络权限变化
    WidgetsBinding.instance.addObserver(this);
    
    // 🔥 延迟检查网络状态，给iOS时间处理权限
    Future.delayed(Duration(milliseconds: 500), () {
      if (mounted) {
        _checkAndRefreshDataAfterNetworkPermission();
      }
    });
  }
  
  // 🔥 使用全局分类数据初始化TabController
  void _initializeTabControllerWithGlobalData() {
    try {
      // 🔥 防止重复初始化
      if (isTabControllerInitialized) {
        debugPrint("CategoryManager: TabController已经初始化，跳过重复初始化");
        return;
      }
      
      final globalCategories = CategoryManager.instance.categories;
      if (globalCategories.isNotEmpty) {
        _tabController?.dispose(); // 🔥 释放之前的Controller
        _tabController = TabController(vsync: this, length: globalCategories.length);
        isTabControllerInitialized = true;
        debugPrint("CategoryManager: 分类页面TabController已初始化，全局分类数量: ${globalCategories.length}");
      } else {
        // 如果全局分类为空，使用备用数据
        _tabController?.dispose(); // 🔥 释放之前的Controller
        _tabController = TabController(vsync: this, length: fallbackCategories.length);
        isTabControllerInitialized = true;
        debugPrint("CategoryManager: 分类页面TabController已初始化，备用分类数量: ${fallbackCategories.length}");
      }
      
      // 🔥 强制刷新UI
      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      debugPrint("CategoryManager: TabController初始化失败: $e");
      // 🔥 出错时使用备用数据
      _tabController?.dispose();
      _tabController = TabController(vsync: this, length: fallbackCategories.length);
      isTabControllerInitialized = true;
      if (mounted) {
        setState(() {});
      }
    }
  }

  @override
  void dispose() {
    // 🔥 移除应用生命周期监听器
    WidgetsBinding.instance.removeObserver(this);
    _tabController?.dispose(); // 🔥 安全释放可空的TabController
    super.dispose();
  }

  // 🔥 监听应用生命周期变化，特别是从后台回到前台
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    if (state == AppLifecycleState.resumed) {
      debugPrint("CategoryManager: 应用回到前台，检查网络状态和数据");
      // 应用回到前台时检查网络状态和数据
      Future.delayed(Duration(milliseconds: 300), () {
        if (mounted) {
          _checkAndRefreshDataAfterNetworkPermission();
        }
      });
    }
  }

  // 🔥 检查网络权限获得后是否需要刷新数据
  void _checkAndRefreshDataAfterNetworkPermission() {
    try {
      final categoryManager = CategoryManager.instance;
      
      // 如果是首次启动或者没有分类数据，尝试获取数据
      if (isFirstLaunch || !categoryManager.hasCategories || categoryManager.isDataExpired) {
        debugPrint("CategoryManager: 检测到可能的网络权限变化，尝试获取分类数据");
        debugPrint("CategoryManager: isFirstLaunch=$isFirstLaunch, hasCategories=${categoryManager.hasCategories}");
        
        // 标记不再是首次启动
        isFirstLaunch = false;
        
        // 重置错误状态
        if (mounted) {
          setState(() {
            isError = false;
            isNetError_kkb = false;
          });
        }
        
        // 尝试获取分类数据
        if (homeBloc != null) {
          homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
        }
      } else {
        debugPrint("CategoryManager: 分类数据已存在且有效，跳过网络请求");
        // 确保TabController已初始化
        if (!isTabControllerInitialized) {
          _initializeTabControllerWithGlobalData();
        }
      }
    } catch (e) {
      debugPrint("CategoryManager: 检查网络权限后刷新数据时出错: $e");
      // 出错时也尝试请求数据
      if (homeBloc != null) {
        homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
      }
    }
  }

  // 🔥 处理刷新按钮点击事件
  void _handleRefreshButtonTap() {
    debugPrint("CategoryManager: 用户点击刷新按钮");
    
    try {
      // 重置所有相关的错误状态和标志位
      setState(() {
        isError = false;
        isNetError_kkb = false;
        error_joy = "Loading...";
        isFirstLaunch = false; // 重置首次启动标记
      });
      
      // 清理之前的TabController状态
      isTabControllerInitialized = false;
      _tabController?.dispose();
      _tabController = null;
      
      // 可选：清除全局分类缓存，强制重新获取数据
      try {
        CategoryManager.instance.clearCategories();
        debugPrint("CategoryManager: 已清除分类缓存");
      } catch (e) {
        debugPrint("CategoryManager: 清除分类缓存失败: $e");
      }
      
      // 重新发起网络请求
      debugPrint("CategoryManager: 刷新按钮 - 重新请求分类数据");
      homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
      
    } catch (e) {
      debugPrint("CategoryManager: 刷新按钮处理失败: $e");
      // 即使出错也尝试发起请求
      homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.backgroundSecondary,
      body: mainbloc()
    );
  }

  Widget mainbloc(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return showMainBuild();
    }, create: (_) {
      homeBloc = JoyHomeBloc();
      
              // 🔥 检查全局分类管理器中是否已有数据
      try {
        final categoryManager = CategoryManager.instance;
        if (!categoryManager.hasCategories || categoryManager.isDataExpired) {
          debugPrint("CategoryManager: 分类页面 - 需要获取分类数据");
          debugPrint("CategoryManager: hasCategories=${categoryManager.hasCategories}, isDataExpired=${categoryManager.isDataExpired}");
          homeBloc.add(GetJOYHomeCategoryEvent(context,appHomeType,""));
        } else {
          debugPrint("CategoryManager: 分类页面 - 使用全局分类数据，分类数量: ${categoryManager.categories.length}");
          // 使用全局分类数据初始化TabController
          _initializeTabControllerWithGlobalData();
        }
      } catch (e) {
        debugPrint("CategoryManager: 访问CategoryManager失败: $e");
        // 🔥 如果CategoryManager出错，直接请求数据
        homeBloc.add(GetJOYHomeCategoryEvent(context,appHomeType,""));
      }
      
      // 🔥 iOS首次启动额外检查，延迟执行以确保网络权限已获得
      Future.delayed(Duration(seconds: 1), () {
        if (mounted && isFirstLaunch) {
          debugPrint("CategoryManager: iOS首次启动延迟检查");
          _checkAndRefreshDataAfterNetworkPermission();
        }
      });

      return homeBloc;
    }, buildWhen: (previousState, state) {
      if(state is GetJOYHomeCategoryEventSuccess){
        isNetError_kkb = false;
        debugPrint("CategoryManager: 分类页面 - API获取分类数据成功");
        // API成功后，数据已自动保存到全局管理器，直接初始化TabController
        _initializeTabControllerWithGlobalData();
        return true;
      }
      
      if(state is GetJOYHomeCategoryEventFailure){
        isNetError_kkb = true;
        String message = state.errMsg ?? "Request failed";
        error_joy = message;
        debugPrint("CategoryManager: 分类页面 - API获取分类数据失败: $message");
        
        // 🔥 失败时检查是否有全局缓存数据，没有才使用备用数据
        try {
          final categoryManager = CategoryManager.instance;
          if (categoryManager.hasCategories) {
            debugPrint("CategoryManager: 分类页面 - 使用全局缓存数据，分类数量: ${categoryManager.categories.length}");
            _initializeTabControllerWithGlobalData();
          } else {
            debugPrint("CategoryManager: 分类页面 - 无缓存数据，使用备用数据");
            _tabController?.dispose();
            _tabController = TabController(vsync: this, length: fallbackCategories.length);
            isTabControllerInitialized = true;
            if (mounted) setState(() {});
          }
        } catch (e) {
          debugPrint("CategoryManager: 失败处理时出错: $e，使用备用数据");
          _tabController?.dispose();
          _tabController = TabController(vsync: this, length: fallbackCategories.length);
          isTabControllerInitialized = true;
          if (mounted) setState(() {});
        }
        return true;
      }

      return false;
    });
  }

  Widget showEmpty(){
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return Column(
      children: [
        Container(
          height: statusBarHeight,
        ),
        Expanded(
          child:  JoyEmptyWidget(
            messageError: error_joy, 
            isNetError: isNetError_kkb, // 🔥 使用实际的网络错误状态
            errorImagePath: "",
            isShowBtn: isNetError_kkb, // 🔥 网络错误时显示刷新按钮
            tapOnCallBack: (){
              // 🔥 点击刷新按钮的回调处理
              _handleRefreshButtonTap();
            }
          ),
        )
      ],
    );
  }

  Widget showMainBuild(){
    // 🔥 使用全局分类管理器检查数据
    final globalCategories = CategoryManager.instance.categories;
    
    // 如果全局管理器没有数据且网络请求失败，显示空状态
    if (globalCategories.isEmpty && isNetError_kkb) {
      return showEmpty();
    }

    final double statusBarHeight = MediaQuery.of(context).padding.top;

    return Stack(
      children: [
        Container(
          color: Colors.transparent,
          margin: EdgeInsets.only(top:statusBarHeight),
          child: Column(
            children: [
              // 🔥 添加网络状态监听组件
              JoyNoNetworkTipWidget(
                haveNetWorkCallBack: (){
                  debugPrint("分类页面：网络已恢复，开始刷新数据");
                  
                  // 🔥 网络恢复时检查分类数据（仅在没有数据或数据过期时获取）
                  try {
                    final categoryManager = CategoryManager.instance;
                    if (!categoryManager.hasCategories || categoryManager.isDataExpired) {
                      debugPrint("CategoryManager: 分类页面网络恢复 - 需要获取分类数据");
                      debugPrint("CategoryManager: 网络恢复时状态 - hasCategories=${categoryManager.hasCategories}, isDataExpired=${categoryManager.isDataExpired}");
                      homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
                    } else {
                      debugPrint("CategoryManager: 分类页面网络恢复 - 分类数据存在且未过期，跳过请求，分类数量: ${categoryManager.categories.length}");
                      // 🔥 确保TabController已经初始化
                      if (!isTabControllerInitialized) {
                        _initializeTabControllerWithGlobalData();
                      }
                    }
                  } catch (e) {
                    debugPrint("CategoryManager: 网络恢复时访问CategoryManager失败: $e");
                    homeBloc.add(GetJOYHomeCategoryEvent(context, appHomeType, ""));
                  }
                  
                  // 重置错误状态和首次启动标记
                  this.isError = false;
                  isNetError_kkb = false;
                  isFirstLaunch = false; // 🔥 网络恢复后标记不再是首次启动
                },
                noNetWorkCallBack: (){
                  debugPrint("分类页面：网络已断开，设置错误状态");
                  this.isError = true;
                },
              ),
              // 主要内容
              Expanded(child: showMain()),
            ],
          ),
        ),
        // DiscordWidget(discordHeight: 470.w,),
      ],
    );
  }
  Widget showMain(){
    final double statusBarHeight = MediaQuery.of(context).padding.top;

    return Container(
      child: Column(
        children: [
          // TabBar 放在顶部
          Container(
            padding: EdgeInsets.symmetric(vertical: 8.h),
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: AppColors.shadow,
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: _tabController == null ? 
              // 🔥 TabController未初始化时显示占位符
              Container(
                height: 50,
                child: Center(
                  child: Text(
                    "Loading categories...",
                    style: TextStyle(fontSize: 14.sp, color: Colors.grey),
                  ),
                ),
              ) :
              TabBar(
                dividerHeight: 0,
                tabAlignment: TabAlignment.start,
                labelPadding: EdgeInsets.only(left: 8,right: 8), // 移除默认内边距
                labelColor: AppColors.primaryVariant,
                indicatorWeight: 1.0,
                automaticIndicatorColorAdjustment: true,
                indicatorPadding: EdgeInsets.symmetric(horizontal: 1.0), // 设置指示器的内边距
                indicator: UnderlineTabIndicator(
                  borderSide: BorderSide(width: 2, color: AppColors.primaryVariant),
                  insets: EdgeInsets.zero,
                ),
                indicatorColor: AppColors.primaryVariant,
                indicatorSize: TabBarIndicatorSize.label,
                unselectedLabelColor: AppColors.garyVariant,
                labelStyle:
                TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w900),
                unselectedLabelStyle:
                TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w400),
                controller: _tabController!,
                isScrollable: true,

                // 🔥 使用全局分类管理器的数据
                tabs: _buildTabsFromGlobalCategories(),
              ),
          ),
          // TabBarView 内容区域
          Expanded(
            child: _tabController == null ?
              // 🔥 TabController未初始化时显示加载状态
              Center(
                child: CircularProgressIndicator(
                  color: Color(0xFFFF6B35),
                ),
              ) :
              TabBarView(
                controller: _tabController!,
                // 🔥 使用全局分类管理器的数据
                children: _buildTabViewsFromGlobalCategories(),
              ),
          ),

        ],
      ),
    );
  }

  // 🔥 构建Tabs，使用全局分类数据或备用数据
  List<Widget> _buildTabsFromGlobalCategories() {
    final globalCategories = CategoryManager.instance.categories;
    
    if (globalCategories.isNotEmpty) {
      // 使用全局分类数据
      return globalCategories.map((category) {
        return Tab(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 8.w),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(category.categoryName),
              ],
            ),
          ),
        );
      }).toList();
    } else {
      // 使用备用数据
      return fallbackCategories.map((category) {
        return Tab(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 8.w),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(category['categoryName']),
              ],
            ),
          ),
        );
      }).toList();
    }
  }

  // 🔥 构建TabViews，使用全局分类数据或备用数据
  List<Widget> _buildTabViewsFromGlobalCategories() {
    final globalCategories = CategoryManager.instance.categories;
    
    if (globalCategories.isNotEmpty) {
      // 使用全局分类数据
      return globalCategories.map((category) {
        return JoyCategoryContentPage(
          categoryName: category.categoryName,
          categoryId: "${category.categoryId}",
        );
      }).toList();
    } else {
      // 使用备用数据
      return fallbackCategories.map((category) {
        return JoyCategoryContentPage(
          categoryName: category['categoryName'],
          categoryId: "${category['categoryId']}",
        );
      }).toList();
    }
  }

}


// 分类内容页面组件